package com.tan.kotlintest.rxjava.rxjavamerga

import android.view.View
import com.tan.kotlintest.R
import com.tan.kotlintest.base.BaseActivity
import com.tan.kotlintest.util.LogUtil
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.annotations.NonNull
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.activity_test_rxjava_merga_layout.*
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.scalars.ScalarsConverterFactory


/*
 * Copyright (C) 2018
 * 版权所有
 *
 * 功能描述： RXJava(merga标签)+Retrofit的结合使用，来同时请求多个网络接口,然后刷新页面
 * 作者：txj
 * 创建时间：2018/9/7
 *
 * 修改人：
 * 修改描述：
 * 修改日期
 */
class TestRxJavaMergaActivity : BaseActivity() {

    var path = "http://app.1-liao.com/app/index.do?userId=127"

    override fun getContentView(): View? {
        return inflate(R.layout.activity_test_rxjava_merga_layout)
    }

    override fun onContentAdded() {
        setTitleText("RXJava+Retrofit的结合使用，同时请求多个网络接口")
        val apiManger = Retrofit.Builder()
                .baseUrl("http://www.yulin520.com/")
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build().create<ApiManger>(ApiManger::class.java)
        val manger = apiManger.getManger(path)
        val observables = ArrayList<Observable<String>>()
        for (i in 0..9) {
            //observables[i] = manger
            observables.add(manger)
        }
        Observable.merge(observables)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<Any> {
                    override fun onSubscribe(@NonNull d: Disposable) {
                        test_tv.text = "开始"
                    }

                    override fun onNext(@NonNull o: Any) {
                        LogUtil.i("请求返回===" + (o as String).toString())
                    }

                    override fun onError(@NonNull e: Throwable) {}

                    override fun onComplete() {
                        LogUtil.i("请求结束")
                        test_tv.text = "结束"
                    }
                })
    }

    private fun getString(): String {
        return "aa"
    }

    private fun getStringOne(): String {
        return getString()
    }

    private fun getStringTwo() = getString()

}